package com.gengzp.rpc.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @ClassName RpcHttpRequestUtils
 * @Description 远程调用http请求工具类
 * @Author gengzp
 * @Date 2025/5/31 23:09
 */
public class RpcHttpRequestUtils {

    private static final RestTemplate restTemplate = initRestTemplate();

    private static RestTemplate initRestTemplate() {
        // 创建基于Apache HttpClient的请求工厂
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        // 配置连接超时时间（毫秒）
        requestFactory.setConnectTimeout(5000);
        // 配置连接请求超时时间（毫秒）
        requestFactory.setConnectionRequestTimeout(10000);
        return new RestTemplate(requestFactory);
    }

    private RpcHttpRequestUtils() {
    }

    /**
     * 发送GET请求
     *
     * @param url          请求URL
     * @param responseType 返回类型
     * @param <T>          泛型
     * @return 响应结果
     */
    public static <T> T get(String url, Class<T> responseType) {
        return restTemplate.getForEntity(url, responseType).getBody();
    }

    /**
     * 发送POST请求
     *
     * @param url            请求URL
     * @param requestHeaders 请求头
     * @param requestBody    请求体
     * @param responseType   返回类型
     * @param <T>            泛型
     * @return 响应结果
     */
    public static <T> T post(String url, Map<String, Object> requestHeaders, Object requestBody, Class<T> responseType) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        if (requestHeaders != null && !requestHeaders.isEmpty()) {
            requestHeaders.forEach((key, value) -> {
                headers.add(key, value.toString());
            });
        }

        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<T> response = restTemplate.postForEntity(url, entity, responseType);
        return response.getBody();
    }

}
